
import { Ref } from 'vue'

// 获取格式化时间（支持传入日期）
export function getDate(date?: Date | string) {
  const da = date ? new Date(date) : new Date()
  const padZero = (num: number) => num.toString().padStart(2, '0')
  
  return `${da.getFullYear()}-${padZero(da.getMonth() + 1)}-${padZero(da.getDate())} ${
    padZero(da.getHours())}:${padZero(da.getMinutes())}:${padZero(da.getSeconds())}`
}

// 获取指定日期所在周的周一（00:00:00）
export function getWeekMonday(date?: Date | string) {
  const today = date ? new Date(date) : new Date()
  const day = today.getDay() || 7
  const monday = new Date(today)
  monday.setDate(today.getDate() - day + 1)
  monday.setHours(0, 0, 0, 0)
  return monday
}

// 获取指定日期所在周的周日（23:59:59）
export function getWeekSunday(date?: Date | string) {
  const today = date ? new Date(date) : new Date()
  const day = today.getDay() || 7
  const sunday = new Date(today)
  sunday.setDate(today.getDate() + (7 - day))
  sunday.setHours(23, 59, 59, 999)
  return sunday
}

// 格式化日期（支持Date对象或Ref<Date>）
export function formatDate(date: Date | string | Ref<Date>) {
  const actualDate = (date && typeof date === 'object' && 'value' in date) 
    ? (date as Ref<Date>).value 
    : new Date(date as string | Date)
  
  if (!(actualDate instanceof Date) || isNaN(actualDate.getTime())) {
    throw new Error('无效的日期参数')
  }
  
  const padZero = (num: number) => num.toString().padStart(2, '0')
  return `${actualDate.getFullYear()}-${
    padZero(actualDate.getMonth() + 1)
  }-${
    padZero(actualDate.getDate())
  }`
}

// 获取上一周周一和周日
export function getPrevWeek(date?: Date | string) {
  const baseDate = date ? new Date(date) : new Date()
  const prevWeekDate = new Date(baseDate.getTime() - 7 * 24 * 3600 * 1000)
  return {
    monday: getWeekMonday(prevWeekDate),
    sunday: getWeekSunday(prevWeekDate)
  }
}

// 获取下一周周一和周日
export function getNextWeek(date?: Date | string) {
  const baseDate = date ? new Date(date) : new Date()
  const nextWeekDate = new Date(baseDate.getTime() + 7 * 24 * 3600 * 1000)
  return {
    monday: getWeekMonday(nextWeekDate),
    sunday: getWeekSunday(nextWeekDate)
  }
}
